package view {
    import flash.utils.Timer;
    import flash.events.TimerEvent;

    /* This class is designed for TimeBar
     * you can bind currentTime for redraw TimeBar,
     * you can change delay when you want
     */

    [Bindable]
    public class GameTimer extends Timer {
        public var currentTime:Number;
        public var down:Boolean;
        private var _totalTime:int;

        // default delay is 1 second
        public function GameTimer(totalTime:int=0, delay:Number=1000, down:Boolean=true) {
            super(delay);
            this.down = down;
            this.totalTime = totalTime;
            this.addEventListener(TimerEvent.TIMER, tick);
        }

        public function set totalTime(time:int):void {
            this._totalTime = time;
            this.resetCurrentTime();
        }

        public function get totalTime():int {
            return _totalTime;
        }

        public function startCount():void {
            this.resetCurrentTime();
            this.reset();
            this.start();
        }

        private function resetCurrentTime():void {
            if (down) {
                this.currentTime = totalTime;
            } else {
                this.currentTime = 0;
            }
        }

        private function tick(event:TimerEvent):void {
            if (down) {
                this.currentTime -= delay/1000;
                if (this.currentTime <= 0) {
                    this.currentTime = 0;
                    this.stop();
                }
            } else {
                this.currentTime += delay/1000;
                if (this.currentTime >= this.totalTime) {
                    this.currentTime = totalTime;
                    this.stop();
                }
            }
        }
    }
}

